<?php


namespace app\common\service;


use app\common\model\ActivityItem;
use app\common\model\ActivityItemViper;
use app\common\model\Goods;

/**
 * 活动管理服务
 *
 * Class ActivityService
 * @package app\common\service
 */
class ActivityService {


    /**
     * 保存活动商品详情信息
     *
     * @param $activity_id     活动ID
     * @param $activity_item   提交商品信息
     */
    public static function saveActivityItem ($activity_id,$activity_item) {
        foreach ($activity_item as $key => $val) {
            if (!empty($val['item'])) {
                $val['item']['activity_id'] = $activity_id;
                $item_data = explode('-',$val['item']['id']);
                $val['item']['item_id'] = $item_data[1];
                $val['item']['item_type'] = $item_data[0];
                unset($val['item']['id']);
                if($item_data[0] == 'goods'){
                    $goods = Goods::where(['id'=>$item_data[1]])->find();
                    if($goods->getAttr('status') == '0'){
                        return ['status'=>false,'msg'=>'【'.$goods->getAttr('name').'】不可售，无法添加组合下单'];
                    }
                }
                $item_model = ActivityItem::create($val['item']);
                if (!empty($val['viper'])) {
                    ActivityService::saveActivityItemViper($item_model['id'],$val['viper']);
                }
            }
        }
        return ['status'=>true];
    }


    /**
     * 保存活动商品详情信息
     *
     * @param $activity_item_id   活动详情ID
     * @param $data
     */
    public static function saveActivityItemViper ($activity_item_id,$viper) {


        foreach ($viper as $key => &$val) {
            $val['activity_item_id'] = $activity_item_id;
            $val['create_time'] = $val['update_time'] = time();
        }

        ActivityItemViper::insertAll($viper);

    }



}